package com.woniuxy.school.user.service.impl;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.woniuxy.commons.core.exception.SchoolException;
import com.woniuxy.commons.core.util.JwtUtil;
import com.woniuxy.school.user.dto.AccountDto;
import com.woniuxy.school.user.dto.LoginDto;
import com.woniuxy.school.user.entity.Account;
import com.woniuxy.school.user.entity.UserInfo;
import com.woniuxy.school.user.from.LoginForm;
import com.woniuxy.school.user.mapper.AccountMapper;
import com.woniuxy.school.user.mapper.UserInfoMapper;
import com.woniuxy.school.user.service.AccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 账号表 服务实现类
 * </p>
 *
 * @author 吴彦祖
 * @since 2025年05月14日
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, Account> implements AccountService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public LoginDto login(LoginForm form)throws Exception {
        LambdaQueryWrapper<Account> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Account::getUsername,form.getUsername());
        wrapper.eq(Account::getType,form.getType());
        Account account = accountMapper.selectOne(wrapper);
        if(account==null){
            throw new SchoolException(10002,"账号不存在");
        }
        if(!account.getPass().equals(form.getPass())){
            throw new SchoolException(10001,"密码错误");
        }
        //更新登陆时间,获取当前时间
        System.out.println(LocalDateTime.now());
        account.setLoginTime(LocalDateTime.now());
        accountMapper.updateById(account);
        LoginDto dto = new LoginDto();
        dto.setType(account.getType());
        if(account.getType()==1){
            dto.setUserId(account.getAdminId());

        }
        if(account.getType()==2){
            dto.setUserId(account.getRepairId());

        }
        if(account.getType()==3){
            dto.setUserId(account.getUserId());

        }
        if(account.getType()==4){
            dto.setUserId(account.getStoreId());

        }

        return dto;

    }

    @Override
    public void sendCode(String phone) throws Exception{
        if(Boolean.TRUE.equals(stringRedisTemplate.hasKey("register:interval:phone:" + phone))){
            throw new Exception("请勿频繁发送验证码");
        }
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,phone);
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if(userInfo!=null){
            throw new Exception("该手机号已经注册过了");
        }
        HashMap<String, Object> params = new HashMap<>();
        params.put("account","C98315611");
        params.put("password","fbab077a6725bd36323113adf1fedf5e");
        params.put("mobile",phone);
        params.put("format","json");
        String code=String.valueOf((int)(Math.random()*9000)+1000);
        System.out.println(code);
        String content="您的验证码是：" + code + "。请不要把验证码泄露给其他人。";
        params.put("content",content);
        //向第三方的接口发送请求
        HttpResponse response = HttpRequest.post("https://106.ihuyi.com/webservice/sms.php?method=Submit").form(params).execute();
        String json = response.body();
        String resultCode = JSONUtil.parseObj(json).get("code").toString();
        if("2".equals(resultCode)){
            stringRedisTemplate.opsForValue().set("register:interval:phone:"+phone,"",1, TimeUnit.MINUTES);
            //                                       每个账号唯一的键名   ,保存的验证码, 1分钟过期,单位.分钟
            stringRedisTemplate.opsForValue().set("register:phone:"+phone,code,1, TimeUnit.MINUTES);
        }else {
            throw new Exception("短信发送失败");
        }
    }

    @Override
    public void add(AccountDto accountDto) throws Exception{
        String code=stringRedisTemplate.opsForValue().get("register:phone:"+accountDto.getPhone());//在redis中根据键取值
        LambdaQueryWrapper<UserInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserInfo::getPhone,accountDto.getPhone());
        UserInfo userInfo = userInfoMapper.selectOne(wrapper);
        if (userInfo != null) throw new SchoolException(400, "手机号已存在");
        if (code == null || !code.equals(accountDto.getCode())) throw new SchoolException(400, "验证码错误");
        LambdaQueryWrapper<Account> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Account::getUsername,accountDto.getUsername());
        Account account = accountMapper.selectOne(wrapper1);
        if (account != null) throw new SchoolException(400, "用户名已存在");
        userInfo = new UserInfo();
        //使用雪花算法生成订单编号
        Snowflake snowflake1 = new Snowflake(1, 1);
        String orderNum1 = snowflake1.nextIdStr();
        userInfo.setId(Long.valueOf(orderNum1));
        userInfo.setUserName(accountDto.getUsername());
        userInfo.setPhone(accountDto.getPhone());
        userInfo.setState(1);
//        userInfo.setCreateUser(accountDto.getUserName());
        userInfo.setCreateTime(LocalDateTime.now());
        userInfoMapper.insert(userInfo);



        account = new Account();
        account.setUsername(accountDto.getPhone());//手机号成为登录账号
        //使用雪花算法生成订单编号
        Snowflake snowflake = new Snowflake(1, 1);
        String orderNum = snowflake.nextIdStr();
        account.setId(Long.valueOf(orderNum));
        account.setUserId(userInfo.getId()+"");
        account.setPass(accountDto.getPass());
        account.setType(3);
        account.setUpdateTime(LocalDateTime.now());
        accountMapper.insert(account);



    }

    public static void main(String[] args) throws Exception {
        String s = JwtUtil.parseUserToken("eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOiI0IiwiZXhwIjoxNzQ3MzgzODAwfQ.IaRbjDMiDOeh3BPwe_OAr2U-1BcqsAjHMIQt63KGre3X8eWJH_7SEJL1bxKx93MJ24k67PqbKdJsdUG9nf-0rQ").get("userId").toString();
        System.out.println(s);
    }
}
